package com.qch.edu.lagou.datastructure.hashmap;

/**
 * @Author qch
 * @Date 2021/7/13
 * 手动hashMap
 */
public class MyHashMap {
    //数组初始化2的n次方
    ListNode[] map = new ListNode[8];
    //ListNode的个数
    int size;

    /**
     * 设置值
     *
     * @param key
     * @param value
     */
    public void put(String key, String value) {

        if (size >= map.length * 0.75) {
            System.out.println("map需要扩容");
            return;
        }//计算索引
        int index = Math.abs(key.hashCode()) % map.length;
        System.out.println("key: "+key+";  index: "+index);
        ListNode ln = map[index];
        if (ln == null)
        {
            //创建单链表
            ListNode lnew=new ListNode();
            //创建头节点
            Node head=new Node(key,value,null);
            //挂载头节点
            lnew.head=head;
            //把单链放在数组里
            map[index]=lnew;
            size++;
        }else {
            //hash碰撞
            //单链表挂节点
            ln.addNode(key,value);
        }
    }

    /**
     * 取值
     * @param key
     * @return
     */
    public String get(String key) {
        int index = Math.abs(key.hashCode()) % map.length;
        ListNode listNode = map[index];
        if(listNode==null)
        {
            return null;
        }
        return listNode.getVal(key);

    }

    public static void main(String[] args) {
        MyHashMap hashMap=new MyHashMap();
        hashMap.put("c1","cccc");
        hashMap.put("m3","kkkk");
        hashMap.put("c1","mmmm");
        //int index = Math.abs("c1".hashCode()) %8;
        //System.out.println(index);
        System.out.println(hashMap.get("c1"));
    }
}
